//
//  PaperItemViewController.swift
//  Exam-iOS
//
//  Created by 李胜锋 on 2018/1/29.
//  Copyright © 2018年 李胜锋. All rights reserved.
//

import UIKit
import SnapKit

class PaperItemViewController: ViewController {
    
    var paperItem: PaperItemModel
    
    var tableView:UITableView!
    ///选择完答案
    public var selectComplete: ((PaperItemModel) -> Void)?
    
    ///编号
    public let index: Int
    
    init(_ paperItem:PaperItemModel, index: Int) {
        self.paperItem = paperItem
        self.index = index
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        tableView = UITableView.init(frame: CGRect.zero, style: .plain)
        tableView.delegate = self
        tableView.dataSource = self
        view.addSubview(tableView)
        tableView.snp.makeConstraints { (make) in
            make.edges.equalTo(UIEdgeInsetsMake(0, 0, 0, 0))
        }
        tableView.backgroundColor = UIColor.lsf_color16(0xf9f9f9)
        tableView.estimatedRowHeight = 44
        tableView.rowHeight = UITableViewAutomaticDimension
        
        tableView.register(PaperItemTitleCell.classForCoder(), forCellReuseIdentifier: "PaperItemTitleCell")
        tableView.register(PaperItemChoiceOptionCell.classForCoder(), forCellReuseIdentifier: "PaperItemChoiceOptionCell")
        tableView.register(PaperItemChoiceAnalysisCell.classForCoder(), forCellReuseIdentifier: "PaperItemChoiceAnalysisCell"
        )
        tableView.register(PaperItemSubjectiveAnalysisCell.classForCoder(), forCellReuseIdentifier: "PaperItemSubjectiveAnalysisCell"
        )
        tableView.register(PaperItemSubjectiverOptionCell.classForCoder(), forCellReuseIdentifier: "PaperItemSubjectiverOptionCell"
        )
        tableView.register(PaperItemSelfRepostCell.classForCoder(), forCellReuseIdentifier: "PaperItemSelfRepostCell"
        )
        
        
        tableView.tableFooterView = UIView()
        tableView.separatorStyle = .none
    }
    
    
    func reload() {
        tableView.reloadData()
    }
    
    ///主观题，保存用户答案
    public func saveAnswer() {

    }
    
}

extension PaperItemViewController: UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        
        if paperItem.method == .analysis {
            tableView.allowsSelection = false
        }
        else {
            tableView.allowsSelection = true
        }
        
        
        var count = 2
        /*
         0: 问题
         1：答案选项列表
         2: 解析
         3: 自评分
         */
        
        if paperItem.method == .analysis {
            count += 1
        }
        ///自评分
        else if paperItem.method == .selfReported {
            count += 2
        }
        
        return count
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        var count = 0
        
        switch section {
            //问题
        case 0:
            count = 1
            
            //答案选项列表
        case 1:
            guard let type = paperItem.type else { return 0 }
            switch type {
            case .radio, .multiSelect, .trueOrFalse:
                count = paperItem.options?.count ?? 0
                
            case .shortAnswer, .analysis, .in_trayTest, .calculation:
                if paperItem.method == .exam {
                    count = 1
                }
            }
            
            //解析
        case 2:
            count = 1
            
            //自评分
        case 3:
            count = 1
        default:
            break
        }
        
        return count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        switch indexPath.section {
        //问题
        case 0:
            let cell = tableView.dequeueReusableCell(withIdentifier: "PaperItemTitleCell") as! PaperItemTitleCell
            cell.set(type:paperItem.type ,content: paperItem.quest, score: paperItem.score)
            return cell
            
            
        //答案选项列表
        case 1:
            switch paperItem.type! {
                
                
                //选择题
            case .radio, .multiSelect, .trueOrFalse:
                let cell = tableView.dequeueReusableCell(withIdentifier: "PaperItemChoiceOptionCell") as! PaperItemChoiceOptionCell
                if let option = paperItem.options?[indexPath.row] {
                    var isSelect = false
                    let answers = paperItem.userAnswer?.components(separatedBy: ",")
                    if answers?.contains(option.id ?? "") == true {
                        isSelect = true
                    }
                    cell.set(id: option.id, desc: option.desc, isSelect: isSelect)
                }
                return cell
                
                //简答题
            case .shortAnswer, .analysis, .in_trayTest, .calculation:
                let cell = tableView.dequeueReusableCell(withIdentifier: "PaperItemSubjectiverOptionCell") as! PaperItemSubjectiverOptionCell
                cell.set(paperItem.userAnswer)
                cell.answerComplete = { [weak self] answer in
                    self?.paperItem.userAnswer = answer
                }
                cell.textView.isUserInteractionEnabled = (paperItem.method == .exam)
                return cell
            }
            
            
            //解析
        case 2:
            guard let type = paperItem.type else { return UITableViewCell() }
            switch type {
                
                //选择题型
            case .radio, .multiSelect, .trueOrFalse:
                let cell = tableView.dequeueReusableCell(withIdentifier: "PaperItemChoiceAnalysisCell") as! PaperItemChoiceAnalysisCell
                cell.set(answers: paperItem.answer, myAnswers: paperItem.userAnswer, analysis: paperItem.analysis, difficulty: paperItem.difficulty)
                return cell
                
                //简答题型
            case .shortAnswer, .analysis, .in_trayTest, .calculation:
                let cell = tableView.dequeueReusableCell(withIdentifier: "PaperItemSubjectiveAnalysisCell") as! PaperItemSubjectiveAnalysisCell
                cell.set(answers: paperItem.answer, myAnswers: paperItem.userAnswer, analysis: paperItem.analysis, difficulty: paperItem.difficulty)
                
                return cell
            }
            
            ///简答题自评分
        case 3:
            let cell = tableView.dequeueReusableCell(withIdentifier: "PaperItemSelfRepostCell") as! PaperItemSelfRepostCell
            cell.maxScore = paperItem.score
            cell.selfReportComplete = { [weak self] score in
                self?.paperItem.userScore = score
                if score == self?.paperItem.score {
                    self?.paperItem.userAnswerResult = PaperItemAnswerResult.correct
                }
                else {
                    self?.paperItem.userAnswerResult = PaperItemAnswerResult.error
                }
            }
            return cell
        default:
            break
        }
        
        return UITableViewCell()
    }
}

extension PaperItemViewController: UITableViewDelegate {
    
    func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool {
        if indexPath.section == 1 {
            return true
        }
        
        return false
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: false)
        
        if indexPath.section == 1 {
            
            guard let options = paperItem.options else { return }
            guard indexPath.row < options.count else { return }
            let option = options[indexPath.row]
            guard let id = option.id else { return }
            //单选，选中
            if paperItem.type == .radio || paperItem.type == .trueOrFalse {
                paperItem.userAnswer = id
            }
                
            //多选题
            else if paperItem.type == .multiSelect {
                
                var oldAnswers = paperItem.userAnswer?.components(separatedBy: ",")
                
                //没有答案，直接赋值
                if oldAnswers == nil {
                    paperItem.userAnswer = id
                }
                    
                    ///已选中，移除
                else if let idx = oldAnswers?.index(of: id) {
                    oldAnswers?.remove(at: idx)
                    paperItem.userAnswer = oldAnswers?.joined(separator: ",")
                }
                    
                    ///未选中，添加
                else {
                    oldAnswers?.append(id) //添加
                    oldAnswers?.sort()  //排序
                    paperItem.userAnswer = oldAnswers?.joined(separator: ",")
                }
            }
            
            ///relaod table view
            let set = IndexSet.init(integer: indexPath.section)
            tableView.reloadSections(set, with: .automatic)
            
            if paperItem.type == .radio || paperItem.type == .trueOrFalse {
                selectComplete?(paperItem)
            }
        }
    }
}


